#include <iostream>
using std::cout;
using std::endl;


//方案二: 嵌套类 + 静态对象
class Singleton
{
    class AutoRelease
    {
    public:
        //在嵌套类中，可以直接访问外部类的静态数据成员_pInstance
        AutoRelease()
        {   
            cout << "AutoRelease()" << endl;
        }

        ~AutoRelease() {
            //在嵌套类中，无法直接访问非静态的数据成员
            //cout << _data << endl;
            if(_pInstance) {
                delete _pInstance;
                _pInstance = nullptr;
            }
            cout << "~AutoRelease()" << endl;
        }
    };
public:
    static Singleton * getInstance()
    {
        if(_pInstance == nullptr){
            _pInstance = new Singleton();
        }
        return _pInstance;
    }
    
    static void destroy()
    {
        if(_pInstance) {
            delete _pInstance;
            _pInstance = nullptr;
        }
    }

    int getData() const {   return _data;   }

private:
    Singleton() {   cout << "Singleton()" << endl;  }
    ~Singleton() {  cout << "~Singleton()" << endl;}

private:
    int _data = 0;
    static AutoRelease _ar;
    static Singleton * _pInstance;
};

Singleton::AutoRelease Singleton::_ar;
Singleton * Singleton::_pInstance = nullptr;


void test0()
{
    Singleton * p1 = Singleton::getInstance();
    Singleton * p2 = Singleton::getInstance();
    cout << "p1:" << p1 << endl;
    cout << "p2:" << p2 << endl;
    cout << p1->getData() << endl;
    cout << p2->getData() << endl;
}


int main()
{
    test0();
    return 0;
}

